from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
from django.contrib.auth import authenticate, logout

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
from .utils import jwt_response_payload_handler
from utils.request_utils import save_login_log
from rest_framework.permissions import AllowAny
from rest_framework.permissions import IsAuthenticated
from rest_framework.exceptions import AuthenticationFailed

from captcha.views import CaptchaStore, captcha_image
import base64
from datetime import datetime
from .models import User

from .serializers import UserSeralizer
from system.serializers import SystemRoleSerializer
from system.models import SystemRole
class CaptchaView(APIView):
    permission_classes = [AllowAny]  # 允许任何用户访问登录接口


    def get(self, request):

        hashkey = CaptchaStore.generate_key()

        imgage = captcha_image(request, hashkey)
        # 将图片转换为base64
        image_base = base64.b64encode(imgage.content)
        data = {
            "uuid": hashkey,
            "img":  image_base.decode("utf-8"),
            "captchaEnabled": True
        }
        return Response(data=data)


class LoginView(APIView):
    permission_classes = [AllowAny]  # 允许任何用户访问登录接口

    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        now_time = datetime.now()
        code = request.data.get('code')
        uuid = request.data.get('uuid')

        # 验证验证码是否有效
        try:
            captcha = CaptchaStore.objects.get(hashkey=uuid, expiration__gt=now_time)
        except CaptchaStore.DoesNotExist:
            save_login_log(request, user_name=username, status=1, msg='登录失败')
            return Response({'error': '验证码已过期'}, status=400)

        if captcha.response != code:
            save_login_log(request, user_name=username, status=1, msg='登录失败')
            return Response({'error': '验证码错误'}, status=400)

        if not username or not password:
            save_login_log(request, user_name=username, status=1, msg='登录失败')
            return Response({'error': '用户名或密码不能为空'}, status=400)

        # 尝试进行用户认证
        user = authenticate(username=username, password=password)
        if user is None:
            save_login_log(request, user_name=username, status=1, msg='登录失败')
            return Response({'error': '登录失败'}, status=400)

        # 登录成功
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        response_data = jwt_response_payload_handler(token=token, user=user, request=request)
        save_login_log(request, user_name=username, status=0, msg='登录成功')

        return Response(response_data)


class LogoutView(APIView):
    def post(self, request):
        # 在这里可以执行一些额外的注销操作，如记录日志等
        logout(request)
        return Response({'message': 'Successfully logged out'})


class LoginUserInfoView(APIView):

    def get(self, request):
        try:
            user = request.user

            login_user_info = {
                'id': user.id,
                'username': user.username,
                # 可以添加更多用户信息
            }
            return Response(login_user_info)
        except Exception as e:
            raise AuthenticationFailed("获取用户信息异常")

class UserInfoView(APIView):
    def get(self, request):

        data_dict = {}
        login_user_info_view = LoginUserInfoView()
        login_user_response = login_user_info_view.get(request)

        if isinstance(login_user_response, Response):
            login_user_id = login_user_response.data.get('id')
            try:
                user_info = User.objects.get(id=login_user_id)
                user = UserSeralizer(user_info).data


                user_role_info = SystemRole.objects.get(role_id=login_user_id)
                user_role = SystemRoleSerializer(user_role_info).data
                user['roles'] = user_role

                data_dict['user'] = user

                data_dict['roles'] = user_role
                data_dict['permissions'] = ["*:*:*"]

                return Response(data_dict)
            except User.DoesNotExist:
                return Response({'error': '用户不存在'}, status=404)
        return login_user_response  # 如果没有获取用户信息则直接返回响应


class UserRoleView(APIView):
    def get(self, request):
        login_user_info_view = LoginUserInfoView()
        login_user_response = login_user_info_view.get(request)

        if isinstance(login_user_response, Response):
            login_user_id = login_user_response.data.get('id')
            try:
                user_info = SystemRole.objects.get(id=login_user_id)
                role_list_data = SystemRoleSerializer(user_info).data
                return Response(role_list_data)
            except User.DoesNotExist:
                return Response({'error': '用户不存在'}, status=404)